//
//  TDWeiZhuanViewController.m
//  TFB
//
//  Created by yull on 15/12/21.
//  Copyright (c) 2015年 TD. All rights reserved.
//

#import "WeiZhuanViewController.h"
#import "MerchantCell.h"
#import "Merchant.h"
#import "MyAccountListCell.h"

#import "SVPullToRefresh.h"

#import "UIButton+Util.h"
#import "UIAlertView+BlocksKit.h"

@interface WeiZhuanViewController () <UITableViewDataSource>

@property (nonatomic, strong) UIView *footerView;

@property (nonatomic, strong) UIButton *currentTypeBtn1;
@property (nonatomic, strong) UIButton *currentTypeBtn2;
@property (nonatomic, strong) NSMutableArray *merchantArray;
@property (nonatomic, strong) NSMutableArray *myAccountArray;
@property (nonatomic, strong) NSMutableArray *myTixianArray;

@property (nonatomic, assign) NSInteger start;

@end

@implementation WeiZhuanViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.navigationItem.title = @"微赚";
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self setupShareRightItem];
    [self setupValidateLeftItem:[[TDUser defaultUser].custStatus isEqualToString:@"2"]];
    
    self.tixianBtn.layer.borderColor = [UIColor colorWithRed:224.0/225.0 green:56.0/255.0 blue:42.0/255.0 alpha:1].CGColor;
    self.tixianBtn.layer.borderWidth = 1;
    self.tixianBtn.layer.cornerRadius = 5;
    self.tixianBtn.layer.masksToBounds = YES;
    
    [self.accountBtn centerImageAndTitle:2];
    [self.merchantBtn centerImageAndTitle:2];
    [self.noticeBtn centerImageAndTitle:2];
    
    [self.accountBtn addTarget:self action:@selector(button_type:) forControlEvents:UIControlEventTouchUpInside];
    [self.merchantBtn addTarget:self action:@selector(button_type:) forControlEvents:UIControlEventTouchUpInside];
    [self.noticeBtn addTarget:self action:@selector(button_type:) forControlEvents:UIControlEventTouchUpInside];
    
    self.appNameL.text = APPNAME;
    [self.FXLevel1Btn setTitle:FX_LEVEL1_NAME forState:0];
    [self.FXLevel2Btn setTitle:FX_LEVEL2_NAME forState:0];
    [self.FXLevel3Btn setTitle:FX_LEVEL3_NAME forState:0];
    [self.FXLevel1Btn addTarget:self action:@selector(button_bottom:) forControlEvents:UIControlEventTouchUpInside];
    [self.FXLevel2Btn addTarget:self action:@selector(button_bottom:) forControlEvents:UIControlEventTouchUpInside];
    [self.FXLevel3Btn addTarget:self action:@selector(button_bottom:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.merchantTableView registerNib:[UINib nibWithNibName:@"MerchantCell" bundle:nil] forCellReuseIdentifier:@"MerchantCell"];
    [self.merchantTableView registerNib:[UINib nibWithNibName:@"MyAccountListCell" bundle:nil] forCellReuseIdentifier:@"MyAccountListCell"];
    self.merchantTableView.rowHeight = 58;
    
    UITextView *footerView = [[UITextView alloc] initWithFrame:CGRectMake(0, 20, CGRectGetWidth(self.view.frame), 60)];
    footerView.editable = NO;
    footerView.textContainerInset = UIEdgeInsetsMake(5, 5, 5, 5);
    footerView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    footerView.textColor = [UIColor colorWithRed:224.0/225.0 green:56.0/255.0 blue:42.0/255.0 alpha:1];
    footerView.text = @"备注：加入代理商及合伙人享受全部下级商户收入";
    footerView.font = [UIFont systemFontOfSize:15];
    self.merchantTableView.tableFooterView = footerView;
    self.footerView = footerView;
    
    __weak typeof(self) wself = self;
    
    [self.merchantTableView addPullToRefreshWithActionHandler:^{
        wself.start = 0;

        if (self.currentTypeBtn1 == self.accountBtn) {
            [wself getMyAccountList];
        }
        
        if (self.currentTypeBtn1 == self.merchantBtn) {
            [wself getMerchantList];
        }
        
        if (self.currentTypeBtn1 == self.noticeBtn) {
            [wself getMyTixianList];
        }
    }];
    
    [self.merchantTableView addInfiniteScrollingWithActionHandler:^{
        if (self.currentTypeBtn1 == self.accountBtn) {
            [wself getMyAccountList];
        }
        
        if (self.currentTypeBtn1 == self.merchantBtn) {
            [wself getMerchantList];
        }
        
        if (self.currentTypeBtn1 == self.noticeBtn) {
            [wself getMyTixianList];
        }
    }];
    
    [self button_bottom:self.FXLevel1Btn];
    
    [self initData];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.bottomView.hidden = NO;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}

- (void)initData {
    
    [self getMerchantList];
    [self getAvailableMoney];
}

- (void)getMerchantList {
    
    Merchant *merchant1 = [[Merchant alloc] init];
    merchant1.merchantName = [NSString stringWithFormat:@"%@数量", FX_LEVEL1_NAME];
    Merchant *merchant2 = [[Merchant alloc] init];
    merchant2.merchantName = [NSString stringWithFormat:@"%@数量", FX_LEVEL2_NAME];
    Merchant *merchant3 = [[Merchant alloc] init];
    merchant3.merchantName = [NSString stringWithFormat:@"%@数量", FX_LEVEL3_NAME];
    Merchant *merchant4 = [[Merchant alloc] init];
    merchant4.merchantName = @"总下级商户数量";
    self.merchantArray = [NSMutableArray arrayWithArray:@[merchant1, merchant2, merchant3, merchant4]];
    
    [TDHttpEngine requestFor_GETMYMERCHANT_WithCustId:[[NSUserDefaults standardUserDefaults] objectForKey:CUST_ID] custMobile:[[NSUserDefaults standardUserDefaults] objectForKey:CUST_MOBILE] complete:^(BOOL succeed, NSString *msg, id reqBody) {
        if (succeed) {
            
            Merchant *merchant1 = self.merchantArray[0];
            merchant1.merchantCount = reqBody[@"level1Count"];
            merchant1.merchantAmt = reqBody[@"level1Amt"];
            Merchant *merchant2 = self.merchantArray[1];
            merchant2.merchantCount = reqBody[@"level2Count"];
            merchant2.merchantAmt = reqBody[@"level2Amt"];
            Merchant *merchant3 = self.merchantArray[2];
            merchant3.merchantCount = reqBody[@"level3Count"];
            merchant3.merchantAmt = reqBody[@"level3Amt"];
            Merchant *merchant4 = self.merchantArray[3];
            merchant4.merchantCount = reqBody[@"allCount"];
            merchant4.merchantAmt = reqBody[@"allAmt"];
            
            [self.merchantTableView reloadData];
        }
        else
        {
            [self.view makeToast:msg duration:2.0f position:@"center"];
        }
    }];
}

- (void)getMyAccountList {
    
    [TDHttpEngine requestFor_GET_MY_BENIFITS_WithCustId:[[NSUserDefaults standardUserDefaults] objectForKey:CUST_ID]
                                             custMobile:[[NSUserDefaults standardUserDefaults] objectForKey:CUST_MOBILE]
                                                  start:self.start
                                               pageSize:10
                                               complete:^(BOOL succeed, NSString *msg, id reqBody) {
                                                   
                                                   if (succeed) {
                                                       
                                                       [self.merchantTableView.pullToRefreshView stopAnimating];
                                                       [self.merchantTableView.infiniteScrollingView stopAnimating];
                                                       
                                                       NSArray *list = [reqBody objectForKey:@"LIST"];
                                                       
                                                       if (self.start == 0) {
                                                           [self.myAccountArray removeAllObjects];
                                                       }
                                                       
                                                       [self.myAccountArray addObjectsFromArray:list];
                                                       
                                                       [self.merchantTableView reloadData];
                                                       self.start += list.count;
                                                       
                                                       if (list.count < 10) {
                                                           self.merchantTableView.showsInfiniteScrolling = NO;
                                                           if (self.myAccountArray.count == 0) {
                                                               self.blankView.hidden = NO;
                                                           }
                                                       }
                                                   }
                                                   else
                                                   {
                                                       [self.view makeToast:msg duration:2.0f position:@"center"];
                                                   }
                                               }];
}

- (void)getMyTixianList {
    
    [TDHttpEngine requestFor_GET_MY_TIXIAN_WithCustId:[[NSUserDefaults standardUserDefaults] objectForKey:CUST_ID]
                                           custMobile:[[NSUserDefaults standardUserDefaults] objectForKey:CUST_MOBILE]
                                                start:self.start
                                             pageSize:10
                                             complete:^(BOOL succeed, NSString *msg, id reqBody) {
                                                 
                                                 if (succeed) {
                                                     
                                                     [self.merchantTableView.pullToRefreshView stopAnimating];
                                                     [self.merchantTableView.infiniteScrollingView stopAnimating];
                                                     
                                                     NSArray *list = [reqBody objectForKey:@"LIST"];
                                                     
                                                     if (self.start == 0) {
                                                         [self.myTixianArray removeAllObjects];
                                                     }
                                                     
                                                     [self.myTixianArray addObjectsFromArray:list];
                                                     
                                                     [self.merchantTableView reloadData];
                                                     self.start += list.count;
                                                     
                                                     if (list.count < 10) {
                                                         self.merchantTableView.showsInfiniteScrolling = NO;
                                                         if (self.myTixianArray.count == 0) {
                                                             self.blankView.hidden = NO;
                                                         }
                                                     }
                                                 }
                                                 else
                                                 {
                                                     [self.view makeToast:msg duration:2.0f position:@"center"];
                                                 }
                                             }];
}

- (void)getAvailableMoney {
    
    [TDHttpEngine requestFor_GET_MONEY_INFO_WithCustId:[[NSUserDefaults standardUserDefaults] objectForKey:CUST_ID]
                                            custMobile:[[NSUserDefaults standardUserDefaults] objectForKey:CUST_MOBILE]
                                              complete:^(BOOL succeed, NSString *msg, id reqBody) {
                                                  
                                                  if (succeed) {
                                                      
                                                      self.moneyL.text = reqBody[@"acBal"];
                                                  }
                                                  else
                                                  {
                                                      [self.view makeToast:msg duration:2.0f position:@"center"];
                                                  }
                                              }];
}

- (IBAction)button_commend:(id)sender {
    
    [self button_share];
}

- (IBAction)button_tixian:(id)sender {
    
    if (self.moneyL.text.doubleValue < 100.0) {
        [self.view makeToast:@"提现金额需大于100" duration:2.0f position:@"center"];
        return;
    }
    
    UIAlertView *alerView = [UIAlertView bk_alertViewWithTitle:@"提现提示" message:[NSString stringWithFormat:@"确定要提现%@?", self.moneyL.text]];
    [alerView bk_setCancelButtonWithTitle:@"取消" handler:^{
        
    }];
    [alerView bk_addButtonWithTitle:@"提现" handler:^{
        
        NSString *txAmt = [NSString stringWithFormat:@"%lu", (unsigned long)[self.moneyL.text doubleValue] * 100];
        
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        [TDHttpEngine requestFor_DRAW_MONEY_WithCustId:[[NSUserDefaults standardUserDefaults] objectForKey:CUST_ID]
                                            custMobile:[[NSUserDefaults standardUserDefaults] objectForKey:CUST_MOBILE]
                                                 txAmt:txAmt
          complete:^(BOOL succeed, NSString *msg, id reqBody) {
              [MBProgressHUD hideHUDForView:self.view animated:YES];
              if (succeed) {
                  self.moneyL.text = @"0.00";
                  [self.view makeToast:@"提现成功" duration:2.0f position:@"center"];
              }
              else
              {
                  [self.view makeToast:msg duration:2.0f position:@"center"];
              }
          }];
    }];
    [alerView show];
}

- (void)button_type:(UIButton *)button {
    
    self.bottomView.hidden = YES;
    
    if (button == self.currentTypeBtn1) {
        return;
    }
    
    self.currentTypeBtn1 = button;
    
    if (button == self.accountBtn) {
        self.merchantTableView.showsPullToRefresh = YES;
        self.merchantTableView.showsInfiniteScrolling = YES;
        
        self.merchantTableView.tableFooterView = [[UIView alloc] init];
        if (!self.myAccountArray) {
            self.start = 0;
            self.myAccountArray = [NSMutableArray array];
            [self getMyAccountList];
        } else {
            if (!self.myAccountArray.count) {
                self.blankView.hidden = NO;
            } else {
                self.start = self.myAccountArray.count;
                self.blankView.hidden = YES;
                [self.merchantTableView reloadData];
            }
        }
    }
    
    if (button == self.merchantBtn) {
        self.merchantTableView.showsPullToRefresh = NO;
        self.merchantTableView.showsInfiniteScrolling = NO;
        
        if (!self.merchantArray) {
            self.start = 0;
            [self getMerchantList];
        } else {
            if (!self.merchantArray.count) {
                self.blankView.hidden = NO;
            } else {
                self.start = self.merchantArray.count;
                self.blankView.hidden = YES;
                self.merchantTableView.tableFooterView = self.footerView;
                [self.merchantTableView reloadData];
            }
        }
    }
    
    if (button == self.noticeBtn) {
        self.merchantTableView.showsPullToRefresh = YES;
        self.merchantTableView.showsInfiniteScrolling = YES;

        self.merchantTableView.tableFooterView = [[UIView alloc] init];
        if (!self.myTixianArray) {
            self.start = 0;
            self.myTixianArray = [NSMutableArray array];
            [self getMyTixianList];
        } else {
            if (!self.myTixianArray.count) {
                self.blankView.hidden = NO;
            } else {
                self.start = self.myTixianArray.count;
                self.blankView.hidden = YES;
                [self.merchantTableView reloadData];
            }
        }
    }
}

- (void)button_bottom:(UIButton *)button {
    
    if (button == self.currentTypeBtn2) {
        return;
    }
    
    self.currentTypeBtn2.backgroundColor = [UIColor clearColor];
    [self.currentTypeBtn2 setTitleColor:[UIColor whiteColor] forState:0];
    button.backgroundColor = [UIColor whiteColor];
    [button setTitleColor:[UIColor colorWithRed:224.0/225.0 green:56.0/255.0 blue:42.0/255.0 alpha:1] forState:0];
    
    [self  setupBottomView:button.tag - 210];
}

- (void)setupBottomView:(NSInteger)type {
    
    NSString *qixiaString = nil;
    NSString *descString = nil;
    if (type == 0) {
        
        self.rateLabel.text = FX_LEVEL1_FEE;
        qixiaString = FX_LEVEL1_QIXIA;
        descString = FX_LEVEL1_DESC;
        self.currentTypeBtn2 = self.FXLevel1Btn;
        
    } else if (type == 1) {
        
        self.rateLabel.text = FX_LEVEL2_FEE;
        qixiaString = FX_LEVEL2_QIXIA;
        descString = FX_LEVEL2_DESC;
        self.currentTypeBtn2 = self.FXLevel2Btn;
        
    } else {
        
        self.rateLabel.text = FX_LEVEL3_FEE;
        qixiaString = FX_LEVEL3_QIXIA;
        descString = FX_LEVEL3_DESC;
        self.currentTypeBtn2 = self.FXLevel3Btn;
        
    }
    
    self.shouyiLabel.attributedText = [self decodeFXString:qixiaString];
    
    if (descString.length) {
        self.illustrateView.hidden = NO;
        self.illustrateLabel.attributedText = [self decodeFXString:descString];
    } else {
        self.illustrateView.hidden = YES;
    }
    
    CGRect adjustRect = self.shouyiLabel.frame;
    adjustRect.size.height = 1000;
    adjustRect.size.width = CGRectGetWidth([UIScreen mainScreen].bounds) - 53;
    
    self.shouyiLabel.frame = [self.shouyiLabel textRectForBounds:adjustRect limitedToNumberOfLines:0];
    if (descString.length) {
        adjustRect.origin = self.illustrateLabel.frame.origin;
        self.illustrateLabel.frame = [self.illustrateLabel textRectForBounds:adjustRect limitedToNumberOfLines:0];
    }
    
    CGRect frame = self.commendBtn.frame;
    frame.origin.y = CGRectGetMaxY(self.shouyiLabel.frame) + 10;
    frame.size.width = CGRectGetWidth([UIScreen mainScreen].bounds) - 16;
    if (descString.length) {
        frame.size.height = CGRectGetMaxY(self.illustrateLabel.frame);
        self.illustrateView.frame = frame;
        frame = self.commendBtn.frame;
        frame.size.width = CGRectGetWidth([UIScreen mainScreen].bounds) - 16;
        frame.origin.y = CGRectGetMaxY(self.illustrateView.frame) + 10;
    }
    self.commendBtn.frame = frame;
    
    self.bottomScrollView.contentSize = CGSizeMake(1, CGRectGetMaxY(self.commendBtn.frame)+10);
}

- (NSMutableAttributedString *)decodeFXString:(NSString *)fxString {
    
    NSMutableAttributedString *returnStr = [[NSMutableAttributedString alloc] init];
    
    NSInteger start = 0;
    NSRange range = [fxString rangeOfString:@"<{color"];
    while (range.length > 0) {
        NSString *tmpStr = [fxString substringWithRange:NSMakeRange(start, range.location - start)];
        [returnStr appendAttributedString:[[NSAttributedString alloc] initWithString:tmpStr attributes:@{NSForegroundColorAttributeName:[UIColor blackColor]}]];
        start = range.location + range.length;
        
        range = [fxString rangeOfString:@"}>" options:NSCaseInsensitiveSearch range:NSMakeRange(start, fxString.length - start)];
        tmpStr = [fxString substringWithRange:NSMakeRange(start, range.location - start)];
        [returnStr appendAttributedString:[[NSAttributedString alloc] initWithString:tmpStr attributes:@{NSForegroundColorAttributeName:[UIColor colorWithRed:224.0/225.0 green:56.0/255.0 blue:42.0/255.0 alpha:1]}]];
        start = range.location + range.length;
        
        range = [fxString rangeOfString:@"<{color" options:NSCaseInsensitiveSearch range:NSMakeRange(start, fxString.length - start)];
    }
    
    [returnStr appendAttributedString:[[NSAttributedString alloc] initWithString:[fxString substringWithRange:NSMakeRange(start, fxString.length - start)] attributes:@{NSForegroundColorAttributeName:[UIColor blackColor]}]];
    
    return returnStr;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (self.currentTypeBtn1 == self.accountBtn) {
        return self.myAccountArray.count;
    } else if (self.currentTypeBtn1 == self.merchantBtn) {
        return self.merchantArray.count;
    } else {
        return self.myTixianArray.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (self.currentTypeBtn1 == self.merchantBtn) {
        MerchantCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MerchantCell" forIndexPath:indexPath];
        
        Merchant *merchant = self.merchantArray[indexPath.row];
        cell.countTypeLabel.text = merchant.merchantName;
        cell.countLabel.text = [NSString stringWithFormat:@"%lld", merchant.merchantCount.longLongValue];
        cell.shouruLabel.text = merchant.merchantAmt;
        
        return cell;
    } else {
        MyAccountListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyAccountListCell"];
        
        if (self.currentTypeBtn1 == self.accountBtn) {
            
            NSDictionary *data = self.myAccountArray[indexPath.row];
            cell.orderIDL.text = data[@"payNo"];
            cell.orderAmtL.text = data[@"amt"];
            cell.orderBenifitL.text = data[@"txnAmt"];
            if ([data[@"balanceState"] integerValue] == 0) {
                cell.orderStatusL.text = @"未结算";
            } else {
                cell.orderStatusL.text = @"已结算";
            }
        } else {
            
            NSDictionary *data = self.myTixianArray[indexPath.row];
            cell.orderIDL.text = data[@"casDate"];
            cell.orderAmtL.text = data[@"txamt"];
            cell.orderBenifitL.text = [data[@"netrecamt"] isKindOfClass:[NSNull class]] ? @"" : data[@"netrecamt"];
            if ([data[@"ordstatus"] integerValue] == 0) {
                cell.orderStatusL.text = @"未处理";
            } else if ([data[@"ordstatus"] integerValue] == 1) {
                cell.orderStatusL.text = @"成功";
            } else {
                cell.orderStatusL.text = @"失败";
            }
        }
        
        return cell;
    }
}

@end
